﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Net;

namespace ST.Buz.Web.Controllers
{
    [Route("sys/enumcode")]
    public class Sys_EnumCodeController : MyBaseController
    {
        private readonly IServiceSysEnumCode service;
        public Sys_EnumCodeController(IServiceSysEnumCode _service,
            ILogger<Sys_EnumCodeController> _logger) : base(_logger)
        {
            service = _service;
        }

        private VMS_Sys_EnumCode GetSearchModelFromJson(JObject paras)
        {
            var vm = new VMS_Sys_EnumCode();
            vm.pnum = TextHelper.GetInt(paras, "pnum");
            vm.psize = TextHelper.GetInt(paras, "psize");
            vm.sortorder = TextHelper.GetString(paras, "sortorder");

            vm.name = TextHelper.GetString(paras, "name");
            vm.value = TextHelper.GetString(paras, "value");
            vm.pid = TextHelper.GetIntNullable(paras, "pid");
            vm.pname = TextHelper.GetString(paras, "pname");
            vm.ids = TextHelper.GetInts(paras, "ids");
            return vm;
        }

        private VMS_Sys_EnumCode GetSearchModelFromGetRequest()
        {
            var vm = new VMS_Sys_EnumCode();
            vm.pnum = TextHelper.GetInt(Request.Query["pnum"]);
            vm.psize = TextHelper.GetInt(Request.Query["psize"]);
            vm.sortorder = TextHelper.GetString(Request.Query["sortorder"]);

            vm.name = TextHelper.GetString(Request.Query["name"]);
            vm.value = TextHelper.GetString(Request.Query["value"]);
            vm.pid = TextHelper.GetIntNullable(Request.Query["pid"]);
            vm.pname = TextHelper.GetString(Request.Query["pname"]);
            vm.ids = TextHelper.GetInts(Request.Query["ids"]);
            return vm;
        }

        private VMS_Sys_EnumCode GetSearchModelFromPostRequest()
        {
            var vm = new VMS_Sys_EnumCode();
            vm.pnum = TextHelper.GetInt(Request.Form["pnum"]);
            vm.psize = TextHelper.GetInt(Request.Form["psize"]);
            vm.sortorder = TextHelper.GetString(Request.Form["sortorder"]);

            vm.name = TextHelper.GetString(Request.Form["name"]);
            vm.value = TextHelper.GetString(Request.Form["value"]);
            vm.pid = TextHelper.GetIntNullable(Request.Form["pid"]);
            vm.pname = TextHelper.GetString(Request.Form["pname"]);
            vm.ids = TextHelper.GetInts(Request.Form["ids[]"]);
            return vm;
        }

        [HttpPost("search")]
        public IActionResult Search([FromBody] JObject paras)
        {
            try
            {
                UserSession sessionCurrent = GetSessionFromRequest();
                var searchModel = GetSearchModelFromJson(paras);
                PageData pageData = service.GetPageList(searchModel);

                return new JsonResultPage(pageData);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        /// <summary>
        /// 根据父级编号获取所有直接下级项目
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        [HttpPost("searchbypcode")]
        public IActionResult SearchByParentCode([FromBody] JObject paras)
        {
            try
            {
                UserSession sessionCurrent = GetSessionFromRequest();

                string parentCode = TextHelper.GetString(paras, "pcode");
                int type = TextHelper.GetInt(paras, "type");
                if (string.IsNullOrEmpty(parentCode))
                {
                    throw new ArgumentException("参数代码不能为空");
                }
                EnumCodeOptionValueType valueType;
                switch (type)
                {
                    case (int)EnumCodeOptionValueType.ID:
                        valueType = EnumCodeOptionValueType.ID;
                        break;
                    case (int)EnumCodeOptionValueType.Name:
                        valueType = EnumCodeOptionValueType.Name;
                        break;
                    case (int)EnumCodeOptionValueType.Value:
                        valueType = EnumCodeOptionValueType.Value;
                        break;
                    default:
                        valueType = EnumCodeOptionValueType.Name;
                        break;
                }
                var result = service.GetChildrenList(parentCode, "", sessionCurrent, valueType);

                return new JsonResultBase(result);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        [ValidateSession]
        [HttpGet("list")]
        public IActionResult List(string code, string title)
        {
            try
            {
                ViewBag.EnumCode = code;
                ViewBag.Title = string.IsNullOrEmpty(title) ? "参数设置" : title;
                ViewBag.CurrentMenu = "37FB4C60B8";//子菜单，需要修改
                UserSession sessionCurrent = GetSessionFromRequest();
                ViewBag.RootOptions = service.GetRootList(sessionCurrent, Base.Enums.EnumCodeOptionValueType.ID);
                if (!string.IsNullOrEmpty(code))
                {
                    service.EnsureCodeValid(code, title, sessionCurrent);
                }
                return View();
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "打开页面失败", (int)HttpStatusCode.InternalServerError);
            }
        }

        [HttpPost("save")]
        public ActionResult Save([FromBody] Sys_EnumCode model)
        {
            try
            {
                CheckParams();

                UserSession sessionCurrent = GetSessionFromRequest();

                int rowID = service.AddOrUpdate(model, sessionCurrent);

                JsonResultBase ret = new JsonResultBase(rowID);
                return ret;
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "保存失败", (int)HttpStatusCode.InternalServerError);
            }
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        [ValidateSession]
        [HttpPost("viewjson")]
        public IActionResult ViewJson([FromBody] JObject paras)
        {
            try
            {
                CheckParams();

                UserSession sessionCurrent = GetSessionFromRequest();
                int id = TextHelper.GetInt(paras, "id");
                var model = service.GetViewDetail(id, sessionCurrent);
                if (model == null)
                {
                    return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
                }

                return new JsonResultBase(model);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        [ValidateSession]
        [HttpPost("editjson")]
        public IActionResult EditJson([FromBody] JObject paras)
        {
            try
            {
                CheckParams();

                UserSession sessionCurrent = GetSessionFromRequest();

                int id = TextHelper.GetInt(paras, "id");

                var model = service.GetEditDetail(id, sessionCurrent);

                if (model == null)
                {
                    return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
                }

                return new JsonResultBase(model);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        [ValidateSession]
        [HttpPost("delete")]
        public JsonResult Delete([FromBody] JObject paras)
        {
            try
            {
                CheckParams();

                UserSession sessionCurrent = GetSessionFromRequest();
                var rowID = TextHelper.GetInt(paras, "id");
                var result = service.Delete(rowID, sessionCurrent);
                return new JsonResultBase(result);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
            }
        }

        /// <summary>
        /// 获取ztree格式数据
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        [HttpPost("ztree")]
        public IActionResult GetZTreeData([FromBody] JObject paras)
        {
            try
            {
                UserSession sessionCurrent = GetSessionFromRequest();

                int? id = TextHelper.GetIntNullable(paras, "id");
                string code = TextHelper.GetString(paras, "code");

                var result = service.GetZTreeDataByID(code, id, sessionCurrent);

                return new JsonResultBase(result);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        /// <summary>
        /// 获取普通的树形列表数据
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        [HttpPost("treejson")]
        public IActionResult GetTreeData([FromBody] JObject paras)
        {
            try
            {
                UserSession sessionCurrent = GetSessionFromRequest();

                int? id = TextHelper.GetIntNullable(paras, "id");
                string code = TextHelper.GetString(paras, "code");

                var result = service.GetDataByPID(id, code, sessionCurrent.OrgID, sessionCurrent);

                return new JsonResultBase(result);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        [HttpPost("setp")]
        public IActionResult SetParent([FromBody] JObject paras)
        {
            try
            {
                UserSession sessionCurrent = GetSessionFromRequest();

                int id = TextHelper.GetInt(paras, "id");
                int pid = TextHelper.GetInt(paras, "pid");

                var result = service.UpdateParent(id, pid, sessionCurrent);

                return new JsonResultBase(result);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        [HttpPost("order")]
        public IActionResult SetOrder([FromBody] SortItem[] items)
        {
            try
            {
                CheckParams();

                UserSession sessionCurrent = GetSessionFromRequest();

                if (items == null || items.Length == 0)
                {
                    throw new ArgumentException("参数不能为空");
                }
                var result = service.UpdateOrder(items, sessionCurrent);

                return new JsonResultBase(result);
            }
            catch (AuthException ex)
            {
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
            }
            catch (BuzException ex)
            {
                return new JsonResultBase(false, ex.Message);
            }
            catch (ArgumentException ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.InnerException ?? ex, ex.Message);
                return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
            }
        }

        [ValidateSession]
        [HttpGet("poplist")]
        public IActionResult PopList(string id, string code, string orgid, string callback)
        {
            ViewData["id"] = TextHelper.GetInt(id);
            ViewData["code"] = code;
            ViewData["orgid"] = TextHelper.GetInt(orgid);
            ViewData["callback"] = string.IsNullOrWhiteSpace(callback) ? "sysEnumCodeCallback" : callback;
            return View();
        }
    }
}